﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Aspectus.BaseClasses;
using HaterAide;
using HaterAide.Interfaces;
using HaterAide.Mappings;
using Utilities.SQL;
using Utilities.Reflection.Emit.Interfaces;
using Utilities.Reflection.Emit.BaseClasses;
using Utilities.Reflection.Emit.Enums;
#endregion

namespace HaterAide.Aspect
{
    /// <summary>
    /// Used by HaterAide ORM to do lazy loading
    /// </summary>
    public class HaterAideAspect : Aspectus.BaseClasses.Aspect
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public HaterAideAspect()
            : base()
        {
            this.InterfacesUsing = new List<Type>();
            this.InterfacesUsing.Add(typeof(IHaterAideObject));
            ClassMappings = ((HaterAide.Settings.AspectSettings)Configuration).ClassMappings;
        }

        #endregion

        #region Aspect Memebers

        public override void SetupInterfaces(Utilities.Reflection.Emit.TypeBuilder TypeBuilder)
        {
            Fields = new List<Utilities.Reflection.Emit.FieldBuilder>();
            IDFields = new List<Utilities.Reflection.Emit.FieldBuilder>();
            ChangedField = CreateProperty(TypeBuilder, "ChangedList0", typeof(List<string>));
            SessionField = CreateProperty(TypeBuilder, "Session0", typeof(Session));
            UpdateField = CreateProperty(TypeBuilder, "Update0", typeof(bool));
            CreateClearChanged(TypeBuilder);
            CreateConstructor(TypeBuilder);
            SetupIDFields(TypeBuilder);
            CreateLoad(TypeBuilder);
        }

        public override void SetupStartMethod(IMethodBuilder Method, Type BaseType)
        {
            Method.SetCurrentMethod();
            if (ClassMappings.ContainsKey(BaseType)
                && Method.Name.StartsWith("set_"))
            {
                IAttributeMap AttributeMap = ClassMappings[BaseType];
                string PropertyName = Method.Name.Replace("set_", "");
                HaterAide.Mappings.Attribute Attribute = AttributeMap.Properties.Find(x => x.Name == PropertyName);
                if (Attribute != null)
                {
                    Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Attribute.DerivedFieldName);
                    if (Field != null)
                        Field.Assign(Method.Parameters[1]);
                    Utilities.Reflection.Emit.Commands.If If = Method.If((VariableBase)ChangedField, Comparison.NotEqual, null);
                    {
                        Method.Call((VariableBase)ChangedField, typeof(List<string>).GetMethod("Add"), new object[] { Attribute.Name });
                    }
                    If.EndIf();
                }
            }
        }

        public override void SetupEndMethod(IMethodBuilder Method, Type BaseType, VariableBase ReturnValue)
        {
            if (ClassMappings.ContainsKey(BaseType)
                && Method.Name.StartsWith("get_"))
            {
                IAttributeMap AttributeMap = ClassMappings[BaseType];
                string PropertyName = Method.Name.Replace("get_", "");
                HaterAide.Mappings.Attribute Attribute = AttributeMap.Properties.Find(x => x.Name == PropertyName);
                if (Attribute != null)
                {
                    if (Attribute.MappingType == AttributeType.Map)
                    {
                        SetupMapProperty(Method, BaseType, ReturnValue, Attribute);
                    }
                    else if (Attribute.MappingType == AttributeType.ManyToOne)
                    {
                        SetupManyToOneProperty(Method, BaseType, ReturnValue, Attribute);
                    }
                    else if (Attribute.MappingType == AttributeType.ManyToMany)
                    {
                        SetupManyToManyProperty(Method, BaseType, ReturnValue, Attribute);
                    }
                    else
                    {
                        SetupReferenceProperty(Method, BaseType, ReturnValue, Attribute);
                    }
                }
            }
        }

        #endregion

        #region Private Functions

        private void CreateLoad(Utilities.Reflection.Emit.TypeBuilder TypeBuilder)
        {
            List<Type> ParameterTypes = new List<Type>();
            ParameterTypes.Add(typeof(SQLHelper));
            IMethodBuilder LoadData = TypeBuilder.CreateMethod("LoadData",
                MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public,
                typeof(void), ParameterTypes);
            {
                LoadData.Call(LoadData.This, typeof(IHaterAideObject).GetMethod("ClearChanged0"), null);
                LoadData.Return();
            }
        }

        private void SetupIDFields(Utilities.Reflection.Emit.TypeBuilder TypeBuilder)
        {
            if (ClassMappings.ContainsKey(TypeBuilder.BaseClass))
            {
                IAttributeMap AttributeMap = ClassMappings[TypeBuilder.BaseClass];
                foreach (HaterAide.Mappings.Attribute Attribute in AttributeMap.Properties)
                {
                    if (Attribute.MappingType == AttributeType.ManyToMany || (Utilities.Reflection.Reflection.IsIEnumerable(Attribute.Type) && Attribute.MappingType == AttributeType.ManyToOne))
                    {
                        foreach (HaterAide.Mappings.Attribute IDAttribute in AttributeMap.IDProperties)
                        {
                            string IDFieldName = "_" + Attribute.Name + "IDDerived";
                            IDFields.Add(TypeBuilder.CreateField(IDFieldName, IDAttribute.Type));
                            Fields.Add(TypeBuilder.CreateField(Attribute.DerivedFieldName, Attribute.Type));
                        }
                    }
                    else if (Attribute.MappingType == AttributeType.Map || Attribute.MappingType == AttributeType.ManyToOne)
                    {
                        foreach (HaterAide.Mappings.Attribute IDAttribute in ClassMappings[Attribute.Type].IDProperties)
                        {
                            string IDFieldName = "_" + Attribute.Name + "IDDerived";
                            IDFields.Add(TypeBuilder.CreateField(IDFieldName, IDAttribute.Type));
                            Fields.Add(TypeBuilder.CreateField(Attribute.DerivedFieldName, Attribute.Type));
                        }
                    }
                }
            }
        }

        private void CreateConstructor(Utilities.Reflection.Emit.TypeBuilder TypeBuilder)
        {
            IMethodBuilder Constructor = TypeBuilder.CreateConstructor();
            {
                Constructor.SetCurrentMethod();
                Constructor.This.Call(TypeBuilder.BaseClass.GetConstructor(Type.EmptyTypes));
                ((VariableBase)ChangedField).Assign(Constructor.NewObj(typeof(List<string>).GetConstructor(Type.EmptyTypes)));
                ((VariableBase)UpdateField).Assign(false);
                Constructor.Return();
            }
        }

        private IPropertyBuilder CreateProperty(Utilities.Reflection.Emit.TypeBuilder TypeBuilder, string Name, Type PropertyType)
        {
            return TypeBuilder.CreateDefaultProperty(Name, PropertyType, PropertyAttributes.SpecialName,
                MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public,
                MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public);
        }

        private void CreateClearChanged(Utilities.Reflection.Emit.TypeBuilder TypeBuilder)
        {
            IMethodBuilder Method = TypeBuilder.CreateMethod("ClearChanged0",
                MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Public,
                typeof(void));
            {
                Method.SetCurrentMethod();
                Method.Call((VariableBase)ChangedField, typeof(List<string>).GetMethod("Clear"), null);
                Method.Return();
            }
        }

        private void SetupReferenceProperty(IMethodBuilder Method, Type BaseType, VariableBase ReturnValue, Mappings.Attribute Attribute)
        {
            Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Attribute.DerivedFieldName);
            if (Utilities.Reflection.Reflection.IsIEnumerable(Attribute.Type))
            {
                Utilities.Reflection.Emit.Commands.If If = Method.If((VariableBase)ChangedField, Comparison.NotEqual, null);
                {
                    Method.Call((VariableBase)ChangedField, typeof(List<string>).GetMethod("Add"), new object[] { Attribute.Name });
                }
                If.EndIf();
            }
        }

        private void SetupManyToManyProperty(IMethodBuilder Method, Type BaseType, VariableBase ReturnValue, Mappings.Attribute Attribute)
        {
            Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Attribute.DerivedFieldName);
            Utilities.Reflection.Emit.FieldBuilder IDField = IDFields.Find(x => x.Name == "_" + Attribute.Name + "IDDerived");
            Utilities.Reflection.Emit.Commands.If If1 = Method.If((VariableBase)SessionField, Comparison.NotEqual, null);
            {
                Utilities.Reflection.Emit.Commands.If If2 = Method.If(Field, Comparison.Equal, null);
                {
                    VariableBase FieldType = Method.CreateLocal(Field.Name + "FieldType", Field.DataType);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.EmitCall(OpCodes.Call, SessionField.GetMethod.Builder, Type.EmptyTypes);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.Emit(OpCodes.Ldfld, IDField.Builder);
                    Method.Generator.Emit(OpCodes.Box, IDField.DataType);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.Emit(OpCodes.Ldflda, Field.Builder);
                    Method.Generator.Emit(OpCodes.Ldstr, Attribute.Name);
                    MethodInfo TempMethod = typeof(HaterAide.Session).GetMethod("SelectList");
                    TempMethod = TempMethod.MakeGenericMethod(new Type[] { BaseType, Field.DataType.GetGenericArguments()[0] });
                    Method.Generator.Emit(OpCodes.Callvirt, TempMethod);
                }
                If2.EndIf();
                Utilities.Reflection.Emit.Commands.If If3 = Method.If(Field, Comparison.Equal, null);
                {
                    Field.Assign(Method.NewObj(Field.DataType.GetConstructor(Type.EmptyTypes)));
                }
                If3.EndIf();
                Utilities.Reflection.Emit.Commands.If If4 = Method.If((VariableBase)ChangedField, Comparison.NotEqual, null);
                {
                    Method.Call((VariableBase)ChangedField, typeof(List<string>).GetMethod("Add"), new object[] { Attribute.Name });
                }
                If4.EndIf();
            }
            If1.EndIf();
            ReturnValue.Assign(Field);
        }

        private void SetupManyToOneProperty(IMethodBuilder Method, Type BaseType, VariableBase ReturnValue, Mappings.Attribute Attribute)
        {
            if (Utilities.Reflection.Reflection.IsIEnumerable(Attribute.Type))
            {
                SetupManyToManyProperty(Method, BaseType, ReturnValue, Attribute);
            }
            else
            {
                SetupMapProperty(Method, BaseType, ReturnValue, Attribute);
            }
        }


        private void SetupMapProperty(IMethodBuilder Method, Type BaseType, VariableBase ReturnValue, Mappings.Attribute Attribute)
        {
            Utilities.Reflection.Emit.FieldBuilder Field = Fields.Find(x => x.Name == Attribute.DerivedFieldName);
            Utilities.Reflection.Emit.FieldBuilder IDField = IDFields.Find(x => x.Name == "_" + Attribute.Name + "IDDerived");
            Utilities.Reflection.Emit.Commands.If If1 = Method.If((VariableBase)SessionField, Comparison.NotEqual, null);
            {
                Utilities.Reflection.Emit.Commands.If If2 = Method.If(Field, Comparison.Equal, null);
                {
                    VariableBase FieldType = Method.CreateLocal(Field.Name + "FieldType", Field.DataType);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.EmitCall(OpCodes.Call, SessionField.GetMethod.Builder, Type.EmptyTypes);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.Emit(OpCodes.Ldfld, IDField.Builder);
                    Method.Generator.Emit(OpCodes.Box, IDField.DataType);
                    Method.Generator.Emit(OpCodes.Ldarg_0);
                    Method.Generator.Emit(OpCodes.Ldflda, Field.Builder);
                    MethodInfo TempMethod = typeof(HaterAide.Session).GetMethod("Select");
                    TempMethod = TempMethod.MakeGenericMethod(new Type[] { Field.DataType });
                    Method.Generator.EmitCall(OpCodes.Call, TempMethod, Type.EmptyTypes);
                }
                If2.EndIf();
                Utilities.Reflection.Emit.Commands.If If4 = Method.If((VariableBase)ChangedField, Comparison.NotEqual, null);
                {
                    Method.Call((VariableBase)ChangedField, typeof(List<string>).GetMethod("Add"), new object[] { Attribute.Name });
                }
                If4.EndIf();
            }
            If1.EndIf();
            ReturnValue.Assign(Field);
        }
        #endregion

        #region Private Properties

        private Dictionary<Type, IAttributeMap> ClassMappings { get; set; }
        private List<Utilities.Reflection.Emit.FieldBuilder> Fields { get; set; }
        private List<Utilities.Reflection.Emit.FieldBuilder> IDFields { get; set; }
        private IPropertyBuilder ChangedField { get; set; }
        private IPropertyBuilder SessionField { get; set; }
        private IPropertyBuilder UpdateField { get; set; }

        #endregion
    }
}